function [outSt,logL]=kfilterReg(parvec,funcmod,Y,trainvec,solveopt,addsol)
% Compared with kfilter_full.m, delivered identical results, Jan 9 2012. 
% ====================================================================
% ====================================================================
%% 1. Model solution
% Matrices of second sample stored in structure second 
[G,R,C,eu,SDX,Z,structOne,~,structTwo]=feval(funcmod,parvec,solveopt,addsol);
% A. Non-existence in either sample 
if isequal(eu,[1;1])==0 
    return
end
[NObs,NZ]=size(Y);
%% 2. Demeaning using the split sample 
%
%  First Sample (C1)
if any(C~=0)==1
    Y=Y-repmat((Z*C)',[NObs 1]);
end
Y=Y';
%% 3. Forward filter 

%% 3.1. Dimensions and storage 
 
NS=size(G,1); 
NX=size(SDX,1); 

vt=zeros(NZ,NObs);
finvt=zeros(NZ,NZ,NObs);
kpartg=zeros(NS,NZ,NObs);
logLnc=zeros(NObs,1); 
yfor =zeros(NZ,NObs);

% Matrices with one additional entry (initialization)
% to recover observables 
stt=zeros(NS,NObs+1);
ptt=zeros(NS,NS,NObs+1);

%% 3.2 Initialization 

stt(:,1)=zeros(NS,1);
P0=feval(@lyapunov_symm,G,R*(SDX')*SDX*R');
ptt(:,:,1)=P0; 

%% 3.3 Start Forward Filter using KF_DK 
% First Part
for ii=1:NObs;
    yfor(:,ii) =Z*(G*stt(:,ii));
    [stt(:,ii+1),ptt(:,:,ii+1),logLnc(ii),vt(:,ii),finvt(:,:,ii),kpartg(:,:,ii)]...
        =feval(@kf_dk,Y(:,ii),Z,stt(:,ii),ptt(:,:,ii),G,R*(SDX'));
end
%% 4. Likelihood with Integration Constant 
logLnc=logLnc(trainvec(1):trainvec(2)); 
logL=-0.5*log(2*pi)*(NZ*NObs)+sum(logLnc);

%% 5. Truncate filters and obtain initial observations 
yferr=vt';
yfor =yfor'; 
stt=stt(:,2:end); 
ptt=ptt(:,:,2:end); 

%% 6. Disturbance smoother with TV matrices 
% Obtain the Innovations using a disturbance smoother 
etamat=zeros(NX,NObs); 
smooth_st=zeros(NS,NObs); 
rmat=zeros(NS,NObs); 

%% 6.1 Initialize RSTAR & start at t=NObs 
rstar=zeros(NS,1); 
Qf =SDX'*SDX;
[rstar,etamat(:,end)]=feval(@smoothdis,rstar,Qf,R',Z',finvt(:,:,end),zeros(NS),vt(:,end));
smooth_st(:,end)=stt(:,end)+ptt(:,:,end)*rstar; 
rmat(:,end)=rstar; 

%% 6.2 Begin Backward recursion 

for ii=(NObs-1):-1:1;
    [rstar,etamat(:,ii)]=feval(@smoothdis,rstar,Qf,R',...
        Z',finvt(:,:,ii),((G-G*kpartg(:,:,ii)*Z)'),vt(:,ii));
    smooth_st(:,ii)=stt(:,ii)+ptt(:,:,ii)*rstar;
    rmat(:,ii)=rstar;
end
a0 = P0*(G')*rstar;   % Note: this is only correct in the case where a0 = zeros(NS,1) 
etamat=(etamat)';
smooth_st=(smooth_st)'; 
stt  =stt'; 

outSt.aZero=a0; 
outSt.aLast=stt(:,end);
outSt.pLast=ptt(:,:,end); 


%% 7. Check Smoother 
% Check that Smooth States are identical if using disturbance smoother (above) vs. state smoother (below) 
% and if can also recover the observables
tol=1e-3; 
% State at time zero give by GG1*azero+Pzero*rstar;
[yCheck,smoothCheck]=feval(@kfilterRegSplitSimulation,a0,etamat'); 
disp('Max Discrepancy Smooth vs. Actual Data'); 
maxdifY=feval(@comparemat,yCheck,Y'); 
disp('Max Discrepancy State and Innovation Smoother'); 
maxdifS=feval(@comparemat,smoothCheck,smooth_st); 
if maxdifY > tol || maxdifS > tol 
    error('Smoother discrepancy exceeds tolerance') 
end 

%% 8. Initial Variance and State per shock (used below for the counterfactual decompositions)
% vInitialPershock: Initial Variance, decomposed per shock 
% sOnePerShock, State at time 1 decomposed, decomposed per shock
vInitialPerShock=zeros(NS,NS,NX);
sZeroSmoothPerShock=zeros(NS,NX); 
sOneSmoothPerShock =zeros(NS,NX); 
for ii=1:NX
    vInitialPerShock(:,:,ii)=feval(@lyapunov_symm,G,R(:,ii)*SDX(ii,ii)*SDX(ii,ii)*(R(:,ii)'));
    sZeroSmoothPerShock(:,ii) = vInitialPerShock(:,:,ii)*(G')*rstar;
    etatemp = zeros(NX,1);
    etatemp(ii) = etamat(1,ii);
    sOneSmoothPerShock(:,ii)=G*sZeroSmoothPerShock(:,ii)...
        +R*etatemp;
end
maxdifSzero=comparemat(sum(sZeroSmoothPerShock,2),a0); 
maxdifSone =comparemat(sum(sOneSmoothPerShock,2),smooth_st(1,:)' ); 
if maxdifSzero > tol; error('Cannot decompose sZeroPerShock'); end 
if maxdifSone > tol; error('Cannot decompose sOnePerShock'); end
%% 9. Counterfactual Decomposition 
% Generate states by feeding each shock at a time, ensure that it recovers
% the original state 
disp('Begin Counterfactual')
countStates=zeros(NObs,NS,NX);
countObs   =zeros(NObs,NZ,NX);
for ii=1:NX
    etaTemp=zeros(NObs,NX); 
    etaTemp(:,ii)=etamat(:,ii); 
    [countObs(:,:,ii),countStates(:,:,ii)]=feval(@kfilterRegSplitSimulation,sZeroSmoothPerShock(:,ii),etaTemp');
end 
disp('Maximum Discrepancy Counterfactual States and Smooth States') 
maxdifCount=comparemat(sum(countStates,3),smooth_st); 
if maxdifCount > tol; error('Counterfactual States do not recover smooth states'); end 

outSt.filteredSt=stt; 
outSt.smoothSt=smooth_st; 
outSt.innovations=etamat; 
outSt.countSt=countStates; 
outSt.countObs=countObs; 
outSt.decompInitialSt=sOneSmoothPerShock; 
outSt.forecastObs=yfor; 
%outSt.forecastError=yferr; 

   
%% Subroutine kfilterRegSplitSimulation allows to simulate the model  
% Inputs 
% sInitial: [NS 1] Initial State 
% innovMat: [Nx Nobx] matrix of innovations 
% By being a sub-routine it has access to all variables defined above 
% Be-careful not to use an index (ii,jj) used above or to repeat variable
% names
    function [ySim,sSim]=kfilterRegSplitSimulation(sInitial,innovMat) 
        if ~isequal(size(innovMat),[NX NObs]) 
            error('Input innovMat must be [NX NObs]') 
        end 
        sSim=zeros(NS,NObs);
        ySim=zeros(size(Y));
        sSim(:,1)=G*sInitial+R*innovMat(:,1);
        ySim(:,1)=Z*sSim(:,1);
        for kk=2:NObs;
            sSim(:,kk)=G*sSim(:,kk-1)+R*innovMat(:,kk);
            ySim(:,kk)=Z*sSim(:,kk); 
        end
        ySim=ySim'; 
        sSim=sSim'; 
    end
%% End of File
end 